package cn.aicnn.chatssespringboot.service.Impl;


import cn.aicnn.chatssespringboot.service.ToolService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class ToolServiceImpl implements ToolService {

    //请求24小时接口
    @Override
    public String getWeatherAnd24(String location) {
        String responseData = "";
        String answer = "";
        // 构建API请求URL
        String apiUrl = "https://api.seniverse.com/v3/weather/hourly.json?key=SlZz-HRm5iC0n0Xst&location="+location+"&language=zh-Hans&unit=c&start=0&hours=24";

        try {
            // 创建HTTP客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(apiUrl);

            // 发送HTTP GET请求
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 处理API返回的数据
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseData = EntityUtils.toString(entity);
                System.out.println("API返回的数据: " + responseData);
                // 在这里解析responseData并提取所需的信息进行输出
                // 在这里解析responseData并提取所需的信息进行输出
                answer = processWeatherDataAnd24(new JSONObject(responseData));
            }

            // 关闭响应
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return answer;
    }

    //处理24小时信息
    @Override
    public String processWeatherDataAnd24(JSONObject response) {
        String responseDatas = "";
        JSONArray results = response.getJSONArray("results");

        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            JSONObject location = result.getJSONObject("location");
            String locationName = location.getString("name");

            JSONArray hourlyData = result.getJSONArray("hourly");
            for (int j = 0; j < hourlyData.length(); j++) {
                JSONObject hourlyInfo = hourlyData.getJSONObject(j);
                String time = hourlyInfo.getString("time");
                String text = hourlyInfo.getString("text");
                String temperature = hourlyInfo.getString("temperature");

                String responseData = "";
                // 使用+=操作符将输出内容连接到responseData字符串
                responseData += "日期: " + time.substring(0, 10) + "\n";
                responseData += "地点: " + locationName + "\n";
                responseData += "时间: " + time.substring(11, 16) + "\n";
                responseData += "天气状况: " + text + "\n";
                responseData += "温度: " + temperature + "℃" + "\n";
                responseData += "----------------------------------" + "\n";
                responseDatas += responseData;
            }
        }
        return responseDatas;
    }

    @Override
    public String getWeatherAndNow(String location) {
        String responseData = "";
        String answer = "";
        // 构建API请求URL
        String apiUrl = "https://api.seniverse.com/v3/weather/now.json?key=SlZz-HRm5iC0n0Xst&location="+location+"&language=zh-Hans&unit=c";

        try {
            // 创建HTTP客户端
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(apiUrl);

            // 发送HTTP GET请求
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 处理API返回的数据
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                responseData = EntityUtils.toString(entity);
                System.out.println("API返回的数据: " + responseData);
                // 在这里解析responseData并提取所需的信息进行输出
                answer = processWeatherDataAndNow(responseData);
            }

            // 关闭响应
            response.close();
            httpClient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return answer;
    }

    @Override
    public String processWeatherDataAndNow(String jsonData) {
        JSONObject response = new JSONObject(jsonData);
        JSONArray results = response.getJSONArray("results");

        StringBuilder responseData = new StringBuilder();

        for (int i = 0; i < results.length(); i++) {
            JSONObject result = results.getJSONObject(i);
            JSONObject location = result.getJSONObject("location");
            String locationName = location.getString("name");

            JSONObject now = result.getJSONObject("now");
            String text = now.getString("text");
            String temperature = now.getString("temperature");
            String windDirection = now.getString("wind_direction");
            String windSpeed = now.getString("wind_speed");
            String humidity = now.getString("humidity");

            responseData.append("地点: ").append(locationName).append("\n");
            responseData.append("天气状况: ").append(text).append("\n");
            responseData.append("温度: ").append(temperature).append("℃").append("\n");
            responseData.append("风向: ").append(windDirection).append("\n");
            responseData.append("风速: ").append(windSpeed).append("m/s").append("\n");
            responseData.append("湿度: ").append(humidity).append("%").append("\n");
            responseData.append("----------------------------------").append("\n");
        }

        return responseData.toString();
    }

    @Override
    public String getWeatherAndFuture(String location) throws Exception {
            String responseData = "";
            String answer = "";
            // 构建API请求URL
            String apiUrl = "https://api.seniverse.com/v3/weather/daily.json?key=SlZz-HRm5iC0n0Xst&location="+location+"&language=zh-Hans&unit=c&start=0&days=5";

            try {
                // 创建HTTP客户端
                CloseableHttpClient httpClient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(apiUrl);

                // 发送HTTP GET请求
                CloseableHttpResponse response = httpClient.execute(httpGet);

                // 处理API返回的数据
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    responseData = EntityUtils.toString(entity);
                    System.out.println("API返回的数据: " + responseData);
                    // 在这里解析responseData并提取所需的信息进行输出
                    answer = processWeatherDataAndFuture(responseData);
                }

                // 关闭响应
                response.close();
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new Exception("获取天气信息失败", e);
            }
        return answer;
    }

    @Override
    public String processWeatherDataAndFuture(String jsonData) throws Exception{
            JSONObject response = new JSONObject(jsonData);
            JSONArray results = response.getJSONArray("results");

            StringBuilder responseData = new StringBuilder();

            for (int i = 0; i < results.length(); i++) {
                JSONObject result = results.getJSONObject(i);
                JSONObject location = result.getJSONObject("location");
                String locationName = location.getString("name");

                JSONArray dailyData = result.getJSONArray("daily");
                responseData.append("地点: ").append(locationName).append("\n");

                for (int j = 0; j < dailyData.length(); j++) {
                    JSONObject dailyInfo = dailyData.getJSONObject(j);
                    String date = dailyInfo.getString("date");
                    String textDay = dailyInfo.getString("text_day");
                    String textNight = dailyInfo.getString("text_night");
                    String highTemp = dailyInfo.getString("high");
                    String lowTemp = dailyInfo.getString("low");
                    String rainfall = dailyInfo.getString("rainfall");
                    String windDirection = dailyInfo.getString("wind_direction");
                    String windSpeed = dailyInfo.getString("wind_speed");
                    String humidity = dailyInfo.getString("humidity");

                    responseData.append("日期: ").append(date).append("\n");
                    responseData.append("白天天气状况: ").append(textDay).append("\n");
                    responseData.append("夜晚天气状况: ").append(textNight).append("\n");
                    responseData.append("最高温度: ").append(highTemp).append("℃").append("\n");
                    responseData.append("最低温度: ").append(lowTemp).append("℃").append("\n");
                    responseData.append("降雨量: ").append(rainfall).append("\n");
                    responseData.append("风向: ").append(windDirection).append("\n");
                    responseData.append("风速: ").append(windSpeed).append("m/s").append("\n");
                    responseData.append("湿度: ").append(humidity).append("%").append("\n");
                    responseData.append("----------------------------------").append("\n");
                }
            }

            return responseData.toString();
    }
}
